import { AppComponentBase } from '@shared/common/app-component-base';
import { Component, OnInit, Injector } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ServiceProxy, UserInfoDTO } from '@shared/service-proxy/service-proxies';

@Component({
  selector: 'app-set-password-modal',
  templateUrl: './set-password-modal.component.html',
  styleUrls: ['./set-password-modal.component.less']
})
export class SetPasswordModalComponent extends AppComponentBase implements OnInit {

  isOkLoading = false;
  validateForm: FormGroup;
  isVisible = false;
  user: UserInfoDTO = new UserInfoDTO();
  constructor(injector: Injector,
    private fb: FormBuilder,
    private _service: ServiceProxy
  ) {
    super(injector);
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      password: [null, [Validators.nullValidator]]
    });
  }

  handleCancel(): void {
    this.close();
  }

  close(): void {
    this.isVisible = false;
  }

  show(id: string) {
    this.user.id = id;
    this.isVisible = true;
  }

  handleOk() {
    this.isOkLoading = true;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    this._service.setPasswordUsingPOST(this.user).subscribe(result => {
      this.isOkLoading = false;
      if (result.success) {
        this.message.success(this.l('save_success'));
        this.close();
      }
      else {
        this.message.info(this.l(result.error.message));
      }
    }, error => {
      this.isOkLoading = false;
      this.message.error(this.l(error.message));
    })
  }
}
